package com.chaoyong.higo.fragment;

import java.io.Serializable;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import org.apache.http.entity.StringEntity;
import org.json.JSONException;
import org.json.JSONObject;

import android.animation.AnimatorSet;
import android.content.Intent;
import android.os.Bundle;
import android.text.style.LineHeightSpan.WithDensity;
import android.view.Display;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.animation.Animation;
import android.view.animation.Animation.AnimationListener;
import android.view.animation.AnimationSet;
import android.view.animation.ScaleAnimation;
import android.view.animation.TranslateAnimation;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.chaoyong.higo.R;
import com.chaoyong.higo.activity.ProductDeTimeActivity;
import com.chaoyong.higo.activity.SearchActivity;
import com.chaoyong.higo.adapter.FragAllGoodsAdapter;
import com.chaoyong.higo.adapter.FragAllGoodsAdapter.OnCartClick;
import com.chaoyong.higo.base.BaseFragment;
import com.chaoyong.higo.bean.GetAllGoodsBean_z;
import com.chaoyong.higo.bean.ListEntity;
import com.chaoyong.higo.net.OApi;
import com.chaoyong.higo.utils.EmptyUtil;
import com.chaoyong.higo.utils.RotateUtil;
import com.chaoyong.higo.utils.V;
import com.chaoyong.higo.utils.Values;
import com.chaoyong.higo.view.BadgeView;
import com.chaoyong.higo.view.MyListView;
import com.chaoyong.higo.view.SelectListView;
import com.chaoyong.higo.view.TitleView;
import com.chaoyong.higo.view.MyListView.OnLoadMoreListener;
import com.chaoyong.higo.view.MyListView.OnRefreshListener;
import com.chaoyong.higo.view.SelectListView.OnSelectListener;
import com.google.gson.Gson;
import com.lidroid.xutils.HttpUtils;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.RequestParams;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.lidroid.xutils.http.client.HttpRequest.HttpMethod;
import com.nostra13.universalimageloader.core.ImageLoader;

public class FragAllGoods_z_bak extends BaseFragment implements OnClickListener, OnRefreshListener, OnLoadMoreListener {

	private TitleView fragshop_title;
	// 全部分类、排序
	private LinearLayout goods_all, goods_new;
	private TextView goods_tv_all, goods_tv_new;
	private ImageView goods_img_all, goods_img_new;
	private int tabStatus = -1;
	// 排序
	private SelectListView mSelectListview;
	//private String[] mAllGoods = { "全部分类", "手机数码", "电脑办公", "家用电器", "化妆个护", "钟表首饰", "其他商品" };
	private String[] mAllGoods;
	private String[] mAgentfeeList = {"价值(高到低)", "价值(低到高)"};
	private String all = "";
	private String news = "";
	
	private int load = 5;
	private Map<String,String> map;

	private MyListView mListview;
	private FragAllGoodsAdapter mAdapter;

	private LinearLayout layout;
	private BadgeView badgeView;
	private GetAllGoodsBean_z bean;
	
	private static ImageView piao;
	private static int width;
	private static int height;
	
	private List<String> keys;
	
	private List<ListEntity> entities;
	
	private ImageView search;

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
		mView = inflater.inflate(R.layout.frag_all_goods_z, container, false);
		return mView;
	}

	
	@Override
	public void findView() {
		initTitleView();

		goods_all = V.f(mView, R.id.goods_all);
		goods_new = V.f(mView, R.id.goods_new);
		goods_img_all = V.f(mView, R.id.goods_img_all);
		goods_img_new = V.f(mView, R.id.goods_img_new);
		goods_tv_all = V.f(mView, R.id.goods_tv_all);
		goods_tv_new = V.f(mView, R.id.goods_tv_new);

		layout = V.f(getActivity(), R.id.main_cart_lay);

		mSelectListview = V.f(mView, R.id.secretary_selectlistview);
		goods_all.setOnClickListener(this);
		goods_new.setOnClickListener(this);

		mListview = V.f(mView, R.id.secretary_lv);
		
		piao = V.f(mView, R.id.goods_piao);
		// 加载更多，刷新
		// mListview.setCanLoadMore(true);
		// mListview.setAutoLoadMore(true);
		// mListview.setCanRefresh(true);
		// mListview.setOnLoadListener(this);
		// mListview.setOnRefreshListener(this);
		mListview.setOnRefreshListener(this);
		mListview.setOnLoadListener(this);
		mListview.setCanLoadMore(true);
		
		search = V.f(mView, R.id.view_right_img);
		search.setVisibility(View.GONE);
	}

	private void initTitleView() {
		fragshop_title = V.f(mView, R.id.fragshops_title_z);

		fragshop_title.setTitleText("所有商品", mContext.getResources().getColor(R.color.home_text));
		fragshop_title.setTitleBack(mContext.getResources().getColor(R.color.white));
		fragshop_title.setRightImage(R.drawable.title_search_orange);
		fragshop_title.setonRightClinck(new OnClickListener() {

			@Override
			public void onClick(View v) {

				// startActivity(new Intent());
				startActivity(new Intent(mContext, SearchActivity.class));
			}
		});
	}

	@Override
	public void init() {
		Display display = getActivity().getWindowManager().getDefaultDisplay();
		width = display.getWidth();
		height = display.getHeight();
		
		badgeView = new BadgeView(mContext, layout);
		badgeView.setBadgeMargin(30, 0);
		badgeView.setBadgeCount(1);

		mSelectListview.setOnSelectListener(new OnSelectListener() {

			@Override
			public void onClick(String name, int position) {
				switch (tabStatus) {
				case 1:
					goods_tv_all.setText(name + "◢");

					//showToast(map.get(name));
					entities.clear();
					switch (position) {
					case 0:
						getClassification("id desc,100");
						break;
					default:
						getClassification("id desc,100," + map.get(name));
						break;
					}
					break;
				case 2:
					goods_tv_new.setText(name + "◢");

					//showToast(position + "000");
					switch (position) {
					case 0:
						// 价值由高到低
						getSort("goods_price desc");
						break;
					case 1:
						getSort("goods_price");
						break;
					}
					break;
				}
			}
		});

		mAdapter = new FragAllGoodsAdapter(mContext);
		mListview.setAdapter(mAdapter);
		// TODO 执行网络查询,填充listView
		
	}
	
	protected void getSort(String order) {
		// TODO Auto-generated method stub
		JSONObject json = new JSONObject();
		try {
			json.put("path", "Home/Goods/index");
			json.put("order", order);
		} catch (JSONException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		RequestParams params = new RequestParams();
		try {
			params.setBodyEntity(new StringEntity(json.toString(), "utf-8"));
		} catch (UnsupportedEncodingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		HttpUtils utils = new HttpUtils();
		utils.send(HttpMethod.POST, Values.SHOP_ALL, params, new RequestCallBack<String>() {

			@Override
			public void onFailure(HttpException arg0, String arg1) {
				// TODO Auto-generated method stub
				showToast(arg1);
			}

			@Override
			public void onSuccess(ResponseInfo<String> arg0) {
				// TODO Auto-generated method stub
				String result = arg0.result;
				Gson gson = new Gson();
				try {
					JSONObject jso = new JSONObject(result);
					JSONObject data = jso.getJSONObject("data");
					try {
						data.getJSONArray("list");
						bean = gson.fromJson(result, GetAllGoodsBean_z.class);
						if (bean.getStatus().equals("1")) {
							entities = bean.getData().getList();
							
							if (!EmptyUtil.isEmpty(entities)) {
								mAdapter.setList(entities);
							}
						}
					} catch (Exception e) {
						// TODO: handle exception
						//showToast("此分类没有数据！");
						//mAdapter.setList(entities);
					}
				} catch (JSONException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				
			}
		});
	}


	protected void getClassification(String string) {
		// TODO Auto-generated method stub
		JSONObject json = new JSONObject();
		try {
			json.put("path", "Home/Goods/index");
			json.put("order", string);
		} catch (JSONException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		RequestParams params = new RequestParams();
		try {
			params.setBodyEntity(new StringEntity(json.toString(), "utf-8"));
		} catch (UnsupportedEncodingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		HttpUtils utils = new HttpUtils();
		utils.send(HttpMethod.POST, Values.SHOP_ALL, params, new RequestCallBack<String>() {

			@Override
			public void onFailure(HttpException arg0, String arg1) {
				// TODO Auto-generated method stub
				showToast(arg1);
			}

			@Override
			public void onSuccess(ResponseInfo<String> arg0) {
				// TODO Auto-generated method stub
				String result = arg0.result;
				Gson gson = new Gson();
				try {
					JSONObject jso = new JSONObject(result);
					JSONObject data = jso.getJSONObject("data");
					try {
						data.getJSONArray("list");
						bean = gson.fromJson(result, GetAllGoodsBean_z.class);
						if (bean.getStatus().equals("1")) {
							entities = bean.getData().getList();
							
							if (!EmptyUtil.isEmpty(entities)) {
								mAdapter.setList(entities);
							}
						}
					} catch (Exception e) {
						// TODO: handle exception
						showToast("此分类没有数据！");
						//mAdapter.setList(entities);
					}
				} catch (JSONException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				
			}
		});
	}


	@Override
	public void onStart() {
		super.onStart();
		
		// httpQueryAllGoods(high, low, items);
				httpQueryAllGoods();

				mAdapter.setOnCartClickListener(new OnCartClick() {
					@Override
					public void onCartClick(String id, String expect, Serializable sb) {
						showToast("已加入到购物车\n" + "商品id:" + id + "\n商品期数:" + expect);
						String goods = id + "," + 1;
						// TODO 添加到购物车，id：商品id，expect:这个字段其实添加的是购买的次数；在调用此接口时候，参数传入“8，9”
						httpAddToCars(goods);
						// 显示数字提醒
						if (badgeView.isShown()) {
							badgeView.increment(1);
						} else {
							badgeView.show();
						}
					}
				});

				mListview.setOnItemClickListener(new OnItemClickListener() {

					@Override
					public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
//						ListEntity entity = bean.getData().getList().get(position-1);
						ListEntity entity = entities.get(position-1);
						Intent i = new Intent(mContext, ProductDeTimeActivity.class);
						i.putExtra("listEntity", entity);
						startActivity(i);
						
//						Page<ListEntity> e = new Page<>();
//						List<ListEntity> le = new ArrayList<>();
//						le.add(entity);
//						e.setList(le);
//						cartProvider.put(entity);
						// showToast(entities.get(position).getGoods_id() + "");
						// entities.get(position).getGoods_id();
					}
				});
				
				getClassification();
	}

	private void getClassification() {
		// TODO Auto-generated method stub
		JSONObject json = new JSONObject();
		try {
			json.put("function", "setAndGet");
			json.put("name", "gps");
		} catch (JSONException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		RequestParams params = new RequestParams();
		try {
			params.setBodyEntity(new StringEntity(json.toString(), "utf-8"));
		} catch (UnsupportedEncodingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		HttpUtils utils = new HttpUtils();
		utils.send(HttpMethod.POST, OApi.Public_appRedis, params, new RequestCallBack<String>() {

			@Override
			public void onFailure(HttpException arg0, String arg1) {
				// TODO Auto-generated method stub
				showToast(arg1);
			}

			@Override
			public void onSuccess(ResponseInfo<String> arg0) {
				String result = arg0.result;
				try {
					JSONObject jso = new JSONObject(result);
					JSONObject data = jso.getJSONObject("data");
					Iterator it = data.keys();
					keys = new ArrayList<String>();
					while (it.hasNext()) {
						String key = it.next().toString();
						keys.add(key);
					}
					Collections.sort(keys);
					map = new HashMap<>();
					map.put("全部分类", "1000");
					mAllGoods = new String[keys.size() + 1];
					mAllGoods[0] = "全部分类";
					for (int i = 0; i < keys.size(); i++) {
						JSONObject js = data.getJSONObject(keys.get(i));
						mAllGoods[i + 1] = js.getString("title");
						map.put(js.getString("title"), js.getString("id"));
					}
				} catch (JSONException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		});
	}


	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.goods_all:// 所有商品
			tabStatus = 1;
			RotateUtil.getInitRotate().setRotate(goods_img_all, R.drawable.secretary_sex);
			mSelectListview.showView(mAllGoods);
			break;
		case R.id.goods_new:// 排序
			tabStatus = 2;
			RotateUtil.getInitRotate().setRotate(goods_img_new, R.drawable.secretary_sex);
			mSelectListview.showView(mAgentfeeList);
			break;
		}
	}

	// 商品的价格高到低
	// private String hight = "goods_price desc";
	private String high = "";
	// 商品的价格低到高
	// private String low = "goods_price";
	private String low = "";
	// 第二个参数不填默认显示10条数据
	// private String items = "goods_price,5";
	private String items = "";

	// private void httpQueryAllGoods(String high, String low, String items) {
	private void httpQueryAllGoods() {
		HttpUtils http = new HttpUtils();
		RequestParams params = new RequestParams();
		JSONObject object;
		try {
			object = new JSONObject();
			object.put("path", "Home/Goods/index");
			// object.put("order", high);
			// object.put("order", low);
			// object.put("order", items);
			object.put("order", "id desc,5,,0,5");
			params.setBodyEntity(new StringEntity(object.toString(), "UTF-8"));
		} catch (JSONException e) {
			e.printStackTrace();
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
		http.send(HttpMethod.POST, Values.SHOP_ALL, params, new RequestCallBack<String>() {

			@Override
			public void onFailure(HttpException arg0, String arg1) {
				showToast("失败" + arg1);
			}

			@Override
			public void onSuccess(ResponseInfo<String> arg0) {
				String result = arg0.result;
				/*try {
					JSONObject jso = new JSONObject(result);
					Iterator it = jso.keys();
					keys = new ArrayList<String>();
					while (it.hasNext()) {
						String key = it.next().toString();
						keys.add(key);
					}
					showToast(keys.get(0) + keys.get(1) + keys.get(2));
				} catch (JSONException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}*/
				
				Gson gson = new Gson();
				bean = gson.fromJson(result, GetAllGoodsBean_z.class);
				if (bean.getStatus().equals("1")) {
					entities = bean.getData().getList();
					
					if (!EmptyUtil.isEmpty(entities)) {
						mAdapter.setList(entities);
					}
				}
			}
		});
	}

	/**
	 * 添加购物车
	 * 
	 * @param goodsIdAndExcept
	 *            拼接方式：id + "," + except
	 */
	private void httpAddToCars(String goodsIdAndExcept) {
		HttpUtils http = new HttpUtils();
		RequestParams params = new RequestParams();
		JSONObject object;
		try {
			object = new JSONObject();
			object.put("app", "1");
			object.put("model", "BuyRecord");
			object.put("function", "addCarList");
			object.put("code", goodsIdAndExcept);
			params.setBodyEntity(new StringEntity(object.toString(), "UTF-8"));
		} catch (JSONException e) {
			e.printStackTrace();
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}

		http.send(HttpMethod.POST, Values.MAIN_RECOMMEND, params, new RequestCallBack<String>() {

			@Override
			public void onFailure(HttpException arg0, String arg1) {
				showToast(arg1);
			}

			@Override
			public void onSuccess(ResponseInfo<String> arg0) {
				try {
					JSONObject object = new JSONObject(arg0.result);
					String status = object.getString("status");
					String data = object.getString("data");
					if (status.equals("1")) {
						showToast(data + "");
					}
				} catch (JSONException e) {
					e.printStackTrace();
				}
			}
		});
	}
	
	public static void onAnimImage(String uri) {
		// TODO Auto-generated method stub
		piao.setVisibility(View.VISIBLE);
		ImageLoader.getInstance().displayImage(Values.BASE_IMAGE_URL + uri, piao);
		
		AnimationSet set = new AnimationSet(true);
		//初始化  
		Animation translateAnimation = new TranslateAnimation(0.1f, width * 3/4,0.1f,height);  
		//设置动画时间                
		//初始化  
		Animation scaleAnimation = new ScaleAnimation(1f, 0.1f,1f, 0.1f);  
		//设置动画时间  
		set.addAnimation(scaleAnimation);
		set.addAnimation(translateAnimation);
		set.setDuration(2000);
		piao.startAnimation(set);
		
		set.setAnimationListener(new AnimationListener() {
			
			@Override
			public void onAnimationStart(Animation animation) {
				// TODO Auto-generated method stub
				
			}
			
			@Override
			public void onAnimationRepeat(Animation animation) {
				// TODO Auto-generated method stub
				
			}
			
			@Override
			public void onAnimationEnd(Animation animation) {
				// TODO Auto-generated method stub
				piao.setVisibility(View.GONE);
			}
		});
	}


	@Override
	public void onRefresh() {
		// TODO Auto-generated method stub
		//showToast("已经刷新啦！");
		/*try {
			Thread.sleep(800);
		} catch (InterruptedException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}*/
		
		//httpRefreshGoods();
		mListview.onRefreshComplete();
	}
	

	
	private void httpLoadMoreGoods() {
		HttpUtils http = new HttpUtils();
		RequestParams params = new RequestParams();
		JSONObject object;
		try {
			object = new JSONObject();
			object.put("path", "Home/Goods/index");
			// object.put("order", high);
			// object.put("order", low);
			// object.put("order", items);
			object.put("order", "id desc,5,," + load +",5");
			params.setBodyEntity(new StringEntity(object.toString(), "UTF-8"));
		} catch (JSONException e) {
			e.printStackTrace();
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
		http.send(HttpMethod.POST, Values.SHOP_ALL, params, new RequestCallBack<String>() {

			@Override
			public void onFailure(HttpException arg0, String arg1) {
				showToast("失败" + arg1);
			}

			@Override
			public void onSuccess(ResponseInfo<String> arg0) {
				String result = arg0.result;
				/*try {
					JSONObject jso = new JSONObject(result);
					Iterator it = jso.keys();
					keys = new ArrayList<String>();
					while (it.hasNext()) {
						String key = it.next().toString();
						keys.add(key);
					}
					showToast(keys.get(0) + keys.get(1) + keys.get(2));
				} catch (JSONException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}*/
				
				try {
					JSONObject jso = new JSONObject(result);
					if(jso.getInt("status") == 0){
						showToast("已经没有更多数据了");
					}else{
						Gson gson = new Gson();
						bean = gson.fromJson(result, GetAllGoodsBean_z.class);
							List<ListEntity> en = bean.getData().getList();
							
							if (!EmptyUtil.isEmpty(en)) {
								entities.addAll(en);
								mAdapter.setList(entities);
							}
					}
				} catch (JSONException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				
			}
		});
	}


	@Override
	public void onLoadMore() {
		// TODO Auto-generated method stub
		httpLoadMoreGoods();
		load = load + 5;
		mListview.onLoadMoreComplete();
	}

}
